package com.service;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

/**
 * version 1.0.0
 *
 * @author KKW
 * @date 2017/7/9.
 */
@Service("jmsService")
public class JMSService {

    @Resource(name = "jmsQueueTemplate")
    private JmsTemplate jmsQTemplate;
    @Resource(name = "jmsTopicTemplate")
    private JmsTemplate jmsTTemplate;

    //创建MessageCreator回调接口，与JmsTemplate组合使用
    class MyMessageCreator implements MessageCreator{
        public String text;
        public void setText(String text){this.text=text;}
        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage(this.text);
        }
    }
    private MyMessageCreator messageCreator;

    public JMSService(){
        messageCreator=new MyMessageCreator();
    }

    /**
     * 发送消息，点对点模式
     * @param s
     */
    public void sendQueue(String s){
        messageCreator.setText(s);
        jmsQTemplate.send(messageCreator);
    }

    /**
     * 发送消息，订阅模式
     * @param s
     */
    public void sendTopic(String s){
        messageCreator.setText(s);
        jmsTTemplate.send(messageCreator);
    }
}
